<template>
  <div>
    <el-row>
      <el-col :span="6">
        <el-form :model="form" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input type="text" v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <el-input type="text" v-model="form.captcha"></el-input>
            <el-row>
              <el-col :span="12" ><img :src="captchaImage" alt="0"/></el-col>
              <el-col :span="12" ><a href="javascript:void(0)" @click="renewCaptcha">看不清，换一张</a></el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {loginApi} from '../api'
import {JSEncrypt} from 'jsencrypt'
export default {
  name: 'login2',
  data () {
    return {
      form: {
        username: '',
        password: '',
        pwd: '',
        captcha: ''
      },
      captchaImage: null,
      rules: {
        password: [
          {required: true, trigger: 'blur', message: '请输入密码'}
        ],
        username: [
          {required: true, trigger: 'blur', message: '请输入用户名'}
        ],
        captcha: [
          {required: true, trigger: 'blur', message: '请输入验证码'}
        ]
      }
    }
  },
  mounted () {
    this.getCaptchaPic()
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 加密密码
          this.form.pwd = this.encryptedData(process.env.PUBLIC_KEY.toString(), this.form.password)
          this.form.password = null
          loginApi.login(this.form, success => {
            this.$message.success('登录成功')
            // 存储token信息，和用户信息
            // 跳转指定页面
            console.log(success)
          }, error => {
            // 验证码过期就刷新验证码
            if (error.message.indexOf('过期') > 0) {
              this.getCaptchaPic()
            }
          })
        } else {
          this.$message.info('表单验证失败')
          return false
        }
      })
    },
    // 加密密码
    encryptedData (publicKey, data) {
      // 新建JSEncrypt对象
      let encryptor = new JSEncrypt()
      // 设置公钥
      encryptor.setPublicKey(publicKey)
      // 加密数据
      return encryptor.encrypt(data)
    },
    getCaptchaPic () {
      loginApi.captcha(null, success => {
        this.captchaImage = 'data:image/png;base64,' + success.data
      })
    },
    // 验证码刷新
    renewCaptcha () {
      this.getCaptchaPic()
    }
  }
}
</script>

<style scoped>

</style>
